package com.graphics;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import com.system.Camera;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * @Author: clm
 * @Date: 2018-10-12
 */

public class GLGraphics {
    public final static int S_GL_VERSION_1X = 1;
    public final static int S_GL_VERSION_2X = 2;
    public final static String S_GL_TAG = "GL";

    private static GLSurfaceView mGLSurfaceView;
    private static Camera sCamera;

    public static void setCamera(Camera camera) {
        sCamera = camera;
    }

    public static Camera getCamera() {
        return sCamera;
    }

    /**
     * 检查设备是否支持gl2.0即以上版本
     * @param context
     * @return
     */
    public static boolean checkDeviceVersionES20(Activity context){
        final ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);

        final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();

        final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000
                ||(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
                &&(Build.FINGERPRINT.startsWith("generic"))
                || Build.FINGERPRINT.startsWith("unknow")
                || Build.MODEL.contains("google_sdk")
                || Build.MODEL.contains("Emulator")
                || Build.MODEL.contains("Android SDK built for x86");

        if (supportsEs2){
            return true;
        }else {
            Toast.makeText(context, "This device does not support OpenGL ES 2.0." ,
                    Toast.LENGTH_SHORT).show();
            return false;
        }
    }
    public static void init(Activity context, int version, GLRender glRender){
        if(mGLSurfaceView == null){
            mGLSurfaceView = new GLSurfaceView(context);
            if(version >= S_GL_VERSION_2X){
                if(checkDeviceVersionES20(context)){
                    mGLSurfaceView.setEGLContextClientVersion(version);
                    Log.e(S_GL_TAG, "当前设备支持GL2.0及更高版本");
                }
                else{
                    Log.e(S_GL_TAG, "当前设备不支持GL2.0及更高版本");
                    return;
                }
            }
            mGLSurfaceView.setRenderer(glRender);
        }
    }

    public static GLSurfaceView getGLSurfaceView() {
        return mGLSurfaceView;
    }
}
